// 获取小程序实例
const appInstance = getApp();

Page({
  data: {
    wrongQuestions: [],  // 初始化页面数据，用于存储全局集合 wrongQuestions
    currentQuestionIndex: 0,  // 当前题目索引
    currentQuestion: {},  // 当前题目对象
    showResult: false  // 是否显示答题结果
  },

  onLoad: function () {
    // 在页面加载时，将全局集合 wrongQuestions 赋值给页面数据 wrongQuestions
    this.setData({
      wrongQuestions: appInstance.globalData.wrongQuestions,
      currentQuestion: appInstance.globalData.wrongQuestions[0]
    });
  },

  checkAnswer: function (e) {
    const selectedIndex = e.currentTarget.dataset.index;
    const correctIndex = this.data.currentQuestion.answer.charCodeAt(0) - 65;

    // 更新选择的答案和正确答案
    this.setData({
      'currentQuestion.selected': selectedIndex,
      'currentQuestion.correct': correctIndex
    });

    if (selectedIndex === correctIndex) {
      // 回答正确，延迟两秒后切换到下一题
      setTimeout(() => {
        this.moveToNextQuestion();
      }, 500);
    } else {
      // 回答错误，不做任何操作
    }
  },

  // 切换到下一题
  moveToNextQuestion: function () {
    if (this.data.currentQuestionIndex < this.data.wrongQuestions.length - 1) {
      this.setData({
        currentQuestionIndex: this.data.currentQuestionIndex + 1,
        currentQuestion: this.data.wrongQuestions[this.data.currentQuestionIndex + 1]
      });
    } else {
      // 全部题目遍历完毕
      wx.showToast({
        title: '已完成复习',
        icon: 'none',
        duration: 2000
      });
      this.setData({
        showResult: true
      });
    }
  }
});
